package userManagement;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import db.DatabaseConnector;

public class EditUser extends HttpServlet {
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
	PrintWriter out = response.getWriter();

	DatabaseConnector DBConnect = new DatabaseConnector(DatabaseConnector.getDatabaseType());

	out.println("<html><head><title>Edit Existing User</title>");
	out.println("<script type=\"text/javascript\" src=\"../userManager.js\"></script></head><body>");
	out.println("<input type=\"hidden\" id=\"passFlag\" value=\"false\" />");

	String SQL;
	String[][] user = null;
	String username;

	//available values are 'edit' and 'existent'
	boolean exists = request.getParameter("loadCase").equals("existent");
	if (exists){
            username = request.getParameter("oldUsername");
            out.println("<h3><font color=\"red\">Username "+request.getParameter("username")
		      + " is already in use! Please select another username or change the name back to '"
		      + username + "'.</font></h3>");
            out.println("<input type=\"hidden\" id=\"oldUsername\" value=\""+request.getParameter("oldUsername")+"\" />");
	} else {
            username = request.getParameter("username");
            SQL = "SELECT * FROM USERS WHERE username = ?";
            user = DBConnect.selectSQL(SQL,2,new String[] {username});
            out.println("<input type=\"hidden\" id=\"oldUsername\" value=\""+username+"\" />");
	}

        //Table 'Users'
        try {
            out.println("<h2 id=\"pageTitle\">Edit User: "+ username +"</h2>");
            out.println("<table><tbody id=\"userPass\">");

            //username
            out.print("<tr><td>Username:</td><td><input type=\"text\" id=\"username\" style=\"width:250px\" value=\"");
            if (exists) {
                out.println(request.getParameter("username") + "\" /></td></tr>");
            } else out.println(user[0][0] +"\" /></td></tr>");

            //password
            out.print("<tr><td>Password:</td><td><input type=\"text\" id=\"password1\" style=\"width:250px\" value=\"");
            if (exists) {
		out.println(request.getParameter("password") +"\" readonly/>");
            } else out.println(user[0][1] +"\" readonly/>");

            out.println("<input type=\"button\" id=\"passButton\" value=\"Change...\" onclick=\"changePassword()\" /></td></tr>");
        } catch (NullPointerException npe){
            out.println("<h3>Error finding User '"+username+"'!</h3>");
            out.println("<p>User '"+username+"' was not found in the database."
			+ "There have been a concurrency problem, or the Users table has had an error occur.</p>");
            out.println("<p>Taking you back to the User Listing...</p>");
	}

        //Table 'User_Info'
	try {
            out.print("<tr id=\"emailRow\"><td>E-mail:</td><td><input type=\"text\" id=\"email\" style=\"width:250px\" value=\"");
            if (exists) {
		out.println(request.getParameter("email")+"\" /></td></tr>");
            } else {
                SQL = "SELECT * FROM USER_INFO WHERE username = ?";
                user = DBConnect.selectSQL(SQL,2,new String[] {username});
                out.println(user[0][1] +"\" /></td></tr>");
            }
        } catch (NullPointerException npe) {
            out.println("<tr id=\"emailRow\"><td>E-mail:</td><td><input type=\"text\" id=\"email\" style=\"width:250px\" /></td></tr>");
	}
        out.println("</tbody></table><br />");

	//Table 'User_Roles' for 'Add User to Group'
	out.print("<b>Groups</b><ul id=\"grouplist\">");
	StringBuffer roleList = new StringBuffer("");
	String[] roles = null;

	if (exists){
            if (!request.getParameter("groups").equals("")){
		roles = request.getParameter("groups").split(";");
		for (int i=0;i<roles.length;i++){
                    out.print("<li>" + roles[i] + "</li>");
                    roleList.append("<option>"+ roles[i] +"</option>");
		}
            } else out.print("<li>(No Groups assigned yet)</li>");

	} else {
            roles = new String[] {"role"};
            user =  DBConnect.selectWhereSQL("USER_ROLES",roles,"username",username);
            try {
                for (int i=0;i<user.length;i++){
                    out.print("<li>" + user[i][0] + "</li>");
                    roleList.append("<option>"+ user[i][0] +"</option>");
		}
            } catch (NullPointerException npe){ //user has no roles
                out.print("<li>(No Groups assigned yet)</li>");
            }
	}
	out.println("</ul>");
	out.println("Add User to Group:<form action=\"addGroup()\">");
	out.println("<select id=\"availList\" style=\"width:150px\">");
	out.println("<option>Select Group...</option>");


	//groups User is not a member of -- Add User to groups
	if (exists) {
            SQL = "SELECT * FROM ROLES";
            user =  DBConnect.selectSQL(SQL,1);
            if (!request.getParameter("groups").equals("")){
                for (int i=0;i<user.length;i++){
                    int l=0;
                    for(int j=0;j<roles.length;j++,l++){
                        if (user[i][0].equals(roles[j])) break;}
                    if (l<roles.length) out.print("<option>" + user[i][0] + "</option>");
		}
            } else {
		for (int i=0;i<user.length;i++){
                    out.print("<option>" + user[i][0] + "</option>");
		}
            }

	} else {
            SQL = "SELECT R.role FROM ROLES R WHERE R.role NOT IN( SELECT U.role FROM USER_ROLES U WHERE U.username=?)";
            user =  DBConnect.selectSQL(SQL,1,new String[] {username});
            for (int i=0;i<user.length;i++){
                out.print("<option>" + user[i][0] + "</option>");
            }
	}
        out.println("</select>");
	out.println("<input type=\"button\" value=\"Add\" onclick=\"addGroup()\" /></form>");

	//remove User from groups
	out.println("Remove User from Group:<br /><form>");
	out.println("<select size=\"1\" id=\"removeList\" style=\"width:150px\">");
	out.println("<option>Select Group...</option>");
	out.println(roleList.toString());
	out.println("</select>");

	out.println("<input type=\"button\" value=\"Remove\" onclick=\"remGroup()\" /></form>");

	out.println("<hr width=\"400px\" align=\"left\" />");
	out.println("<div style=\"width:400px\"><center>");
	out.println("<form method=\"post\" action=\"ListUsers\">");
	out.println("<input type=\"button\" value=\"Save Changes\" onclick=\"submitUser()\" style=\"font:bold 14px Times New Roman\" />");
	out.println("<input type=\"submit\" value=\"Return to User List\" /></form></center></div>");

        out.println("</body></html>");
        out.close();

        DBConnect.CleanUp();
    }

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
			doPost(request, response);
	}
}